$(function () {
	// 设置日期格式
	function formatDate(time){
		time = new Date(time);
		var am = "";
		var y = time.getFullYear();		
		var M = time.getMonth()+1;
		var d = time.getDate();
		var h = time.getHours();
		var m = time.getMinutes();
		M = M<10 ? "0"+M : M;
		d = d<10 ? "0"+d : d;
		h = h<10 ? "0"+h : h;
		m = m<10 ? "0"+m : m;
		if(h<=12){
			am = "上午";
		}else{
			am = "下午"
		}
		return y+"-"+M+"-"+d+" "+am+" "+h+":"+m;
	}
	
	// 返回按钮
	$("#goback").click(function () {
		location.href = 'index3.html';
	});
	// 设置按钮
	$(".settings").on("click", function () {
		$(".settingsC").slideToggle();
	});
	var timer = "";
	var totalHeight = $("#reply")[0].scrollHeight + 44 + $("#themeSection").height();

	// 回到顶部事件
	$("#backTop").click(function (event) {
		$("html,body").animate({
			scrollTop: 0
		}, 500).stop();
	});
	// 到底部按钮事件
	$("#backBottom").click(function () {
		var vh = $("#reply")[0].scrollHeight + $("#themeSection").height() - $(window).height() + 44;
		$("html,body").animate({
			scrollTop: vh
		}, 500).stop();
	});
	/**********************请求***********************************/
	var dataCount = 0;
	var themeHtml = "";
	var replyHtml = "";
	var sectionId = "";
	var isLoading = false; //是否上拉加载  up
	var subed;
	var data = {
		id: getQueryVariable('id'),
		com_id:getQueryVariable('com_id')
	};
	// 发送获取留言请求
	$.ajax({
		type: "get",
		url: "/theme",
		async: true,
		data: data
	}).done(function (resData, status, jqXHR) {
		console.log(resData);
		themeHtml = template("themeSection1", resData.theme);
		$("#themeSection").html(themeHtml);
		var html = resData.theme.content ;
		$(".message").eq(0).html(html);
		
		var time = formatDate($(".sectionTimeO").text())
		$(".sectionTimeO").text(time);
		subed = resData.subed;
		if (subed) {
			$('.subscribe').data("sub", true).removeClass("glyphicon-eye-close").addClass("glyphicon-eye-open").css("color", "white");
		} else {
			$('.subscribe').data("sub", false).removeClass("glyphicon-eye-open").addClass("glyphicon-eye-close").css("color", "#f0f0f0");
		}
		sectionId = resData.theme.id;
		if (resData.reply) {
		
			replyHtml = template("replyContainer", resData);
			// console.log(replyHtml);
			$("#reply").html(replyHtml);
			$("#reply").slideDown(); // up
			var htmls = [];
			for(var i=0;i<resData.reply.length;i++){
				htmls.push(resData.reply[i].content);
			}
			$(".mc").each(function(index){
				
					$(this).html(htmls[index]);
				
			});
			dataCount = resData.reply.length;
			$(".dataCount").text(dataCount);
			var time = formatDate($(".sectionTime").text());
//			$(".sectionTime").text(time);
		}
		// up 判断回复的长度是否大于默认请求加载数据的长度
		if (resData.reply.maxLimit) {
			// 如果回复长度大于默认请求加载数据的长度
			$(".loading").show();
			isLoading = true;
		}else{
//			$("body").css("overflow","hidden");
		}
		if (resData.theme.user_info.id== $.cookie("wcID")) {
			$(".settings").fadeIn();
			$(".deleteReply").show().parent().css("width", 230);
		}
	}).fail(function (jqXHR, status, error) {
		console.log(error);
	});
	var favaCount = "";
	// 点赞数加1
	var lCount = 0;
	// 点赞请求延时
	var resLikeTimeout;

	$("#themeSection").on("click", ".likeWC", function () {
		var likebool = true;
		var arg = arguments;

		favaCount = $(this).next().text();
		lCount++;
		if (!$(this).data("like")) {
			favaCount++;
			$(this).data("like", true);
		} else {
			favaCount--;
			$(this).data("like", false);
		}

		// console.log($(this).data('like'));
		console.log(lCount);
		console.log(likebool);
		if (lCount > 10 && likebool) {
			headerTit("您请求的次数过于频繁，请5s后再试");
			$("#themeSection").off("click", ".likeWC");
			liketimeout = setTimeout(function () {
				$("#themeSection").on("click", ".likeWC", arg.callee);
				likebool = false;
				lCount = 0;
			}, 5000);
		} else {
			if ($(this).data("like")) {
				$(this).removeClass("glyphicon-heart-empty").addClass("glyphicon-heart").next().text(favaCount);
				$.cookie("like",true);
				headerTit("已点赞"); // up

			} else {
				$(this).addClass("glyphicon-heart-empty").removeClass("glyphicon-heart").next().text(favaCount);
				headerTit("取消点赞"); //up
//				$.cookie("like",false);
			}
			clearTimeout(resLikeTimeout);
			console.log(favaCount);
			
			var obj = {
				sectionId,
				favaCount,
				likebool: $('#themeSection .likeWC').data('like')
			};
			resLikeTimeout = setTimeout(function () {
				// console.log('aaaa');
				$.ajax({
					type: "post",
					url: "/comment/like",
					data: obj,
					success: function (response) {
						
					}
				});
			}, 3000);
		}


	});
	
	

	// 顶部的删除按钮事件

	$("header").on("click", ".deleteComment", function () {
		if (confirm("是否删除所有")) {
			$.ajax({
				type: "post",
				url: "/deleteComment",
				data: sectionId,
				async: true
			}).done(function (status, resData, jqXHR) {
				if (resData.code == 1) {
					alert("删除成功");
					$("#reply").empty();
				}
			}).fail(function (jqXHR, status, error) {
				alert("删除失败");
			});
		}

	});
	//up 头部标签底下的提示框事件
	function headerTit(str) {
		$(".titleMessage").slideDown().find("span").text(str);
		setTimeout(function () {
			$(".titleMessage").slideUp();
		}, 3000);
	}
	// 点击次数
	var count = 0;
	//	var isTimeDown = false;
	var subTimeout;
	//up 点击订阅图标订阅
	var subbool = false;
	$(".subscribe").on("click", function () {
		subbool = true;
		count++;
		var arg = arguments;
		var obj = "";
		if (!$(this).data("sub")) {
			obj = {
				sectionId,
				isSub: true
			};
		} else {
			obj = {
				sectionId,
				isSub: false
			};
		}
		if (count > 10 && subbool) {
			headerTit("您请求的次数过于频繁，请5s后再试");
			$(".subscribe").off("click");
			setTimeout(function () {
				$(".subscribe").on("click", arg.callee);
				subbool = false;
				count = 0;
			}, 5000);
		} else {
			if (obj.isSub) {
				$(this).data("sub", true).removeClass("glyphicon-eye-close").addClass("glyphicon-eye-open").css("color", "white");
				headerTit("已订阅此主题");
				clearTimeout(subTimeout);
				subTimeout = setTimeout(function () {
					$.ajax({
						type: "get",
						url: "/users/subscribe",
						data: obj,
						success: function (response) {}
					});
				}, 2000)
			} else {
				$(this).data("sub", false).removeClass("glyphicon-eye-open").addClass("glyphicon-eye-close").css("color", "#f0f0f0");
				headerTit("取消订阅此主题");
				clearTimeout(subTimeout);
				subTimeout = setTimeout(function () {
					$.ajax({
						type: "post",
						url: "/comment/delete",
						data: {id:sectionId,tableName:'Subscribe'},
						success: function (response) {}
					});
				}, 2000)
			}

		}




	});

	// 点击 评论的事件
	$("#reply").on("click", "li", function () {
		$(this).addClass("animated flipInX").find(".guard").fadeIn(1000);
	});
	// 点击 取消按钮事件
	$("#reply").on("click", ".gCancel", function (event) {
		event.stopImmediatePropagation();
		$(this).parents("li").removeClass("animated flipInX").find(".guard").fadeOut(1000);
	});
	// 点击回复按钮事件
	$("#reply").on("click", ".gReply", function (event) {
		event.stopImmediatePropagation();
		if (!$.cookie("wcID")) {
			if (confirm("您尚未登陆是否为您跳转到登陆界面")) {
				location.href = "register2.html";
				$(this).parents("li").removeClass("animated flipInX").find(".guard").fadeOut(1000);
			}
		} else {
			var com_id = $(this).parents("li").find(".sectionID").data('id');
			var authorId = $(this).parents("li").find(".authorId").text();
			var theme_id = $('#themeSection').find(".sectionID").text();
			console.log(com_id);
			console.log(theme_id);
			// var obj = {
			// 	data,
			// 	userId: $.cookie("wcID"),
			// 	authorId
			// };
			// $.get("/replySection", obj, function () {});
			location.href = '/post.html?com_id=' + com_id + '&id=' + theme_id;
		}
	});
	// 点击删除按钮事件
	$("#reply").on("click", ".deleteReply", function (event) {
		event.stopImmediatePropagation();
		var data = $(this).parents("li").find(".sectionID").text();
		var obj = {
			sectionId,
			authorId: data
		}
		var $this = $(this).parents("li");
		$.get("/deleteReply", obj, function (resData) {
			if (resData.code == 1) {
				$this.fadeOut(600);
			}
		});
	});
	// 上拉加载
	$(window).scroll(function () {
		clearTimeout(timer);
		$(".shortcutBtn").fadeIn();
		timer = setTimeout(function () {
			$(".shortcutBtn").fadeOut();
		}, 1000);
		var vx = $(window).scrollTop();
		var vh = $(window).height();
		var total = vx + vh;
		if (isLoading) { // up
			if (total >= totalHeight - 10) {
				$(".loading").css({
					backgroundImage: "url(img/loading_010.gif)",
					backgroundRepeat: "no-repeat",
					backgroundPosition: "50% 0"
				}).find("div").hide();
				page = page + 1;
				var data = {
					dataCount,
					sectionId
				}
				$.ajax({
					type: "get",
					url: "/thmem",
					async: true,
					data: {
						page: page
					}
				}).done(function (resData) {
					if (resData.total > page) {
						htmlStr = template("mainTemplate", resData);
						$("#reply").append(htmlStr);
						totalHeight = $("#reply")[0].scrollHeight + 44 + $("#themeSection").height();
						var htmls = [];
						for(var i = 0;i<resData.reply.length;i++){
							htmls.push(resData.reply[i].content)
						}
						
						
						dataCount += dataCount + resData.length;
						$(".dataCount").text(dataCount);
						$(".loading").css("background-image", "").find("div").show().find(".iconM").show().next().text("上拉加载");
					} else {
						$(".loading").css("background-image", "").find("div").show().html("<p>没有更多的数据</p>");
					}
				}).fail(function (jqXHR, status, error) {
					$(".loading").css("background-image", "").find("div").show().html("<p><span class='glyphicon glyphicon-remove'></span>&nbsp;加载失败</p>");
				})
			}
		}
	});

	function getQueryVariable(variable) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
		return (false);
	}

	$('#themeSection').on('click', '.readWC', function () {
		location.href = '/post.html?id=' + sectionId;
	})

});


//window.onbeforeunload = function () {
//	if ($(".likeWC").data("like")) {
//		$.post("/section", favaCount, function () {});
//	};
//	// 如果订阅此主题了,发送订阅请求
//	// up
//	if($(".subscribe").data("sub")){
//		$.post("/sectionSub",function () {});
//	}
//}